<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Banner;
use app\common\model\coupon\Coupon as CouponCoupon;
use app\common\model\coupon\Log;
use app\common\model\User;
use Exception;

/**
 * 优惠券接口
 */
class Coupon extends Api
{
    protected $noNeedLogin = ['list'];
    protected $noNeedRight = ['*'];
    /**
     * @Author LK
     * @ApiTitle (优惠券列表)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="商户ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function list()
    {
        $param = request()->param();
        extract($param);
        $ids =  Log::where('user_id', $this->auth->id)->where('shop_id', $id)->column('coupon_id');
        $coupon = CouponCoupon::whereNotIn('id', $ids)->paginate(10);
        $this->success('请求成功', $coupon);
    }
    /**
     * @Author LK
     * @ApiTitle (优惠券领取)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="优惠劵ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function receive()
    {
        $post = request()->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        try {
            Log::getCoupon($id, $this->auth->id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('领取成功');
    }
    /**
     * @Author LK
     * @ApiTitle (我的优惠券)
     * @ApiMethod (GET)
     * @ApiParams (name="shop_id", type="integer", required=true, sample="", description="下单时传参商户ID")
     * @ApiParams (name="pay_money", type="integer", required=true, sample="", description="下单时传参付款金额")
     * @ApiParams (name="pay_type", type="integer", required=true, sample="", description="使用场景:use=下单可使用优惠劵；unused=我的优惠劵列表")
     * @ApiParams (name="type", type="integer", required=true, sample="", description="状态值:0=过期,1=正常,2=已使用")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function myCoupon()
    {
        $get = request()->get();
        extract($get);
        if (!isset($type) || !$type) {
            $this->error('参数错误');
        }
        try {
            $user_id =  $this->auth->id;
            $couponLog = new Log();
            $list = $couponLog->getUseCoupon($type, $user_id, $pay_type, $pay_money ?? 0, $shop_id ?? 0);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('请求成功', $list);
    }
}
